﻿#include "docmanage.h"
#include "ui_docmanage.h"
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QFile>
#include <QFileDialog>
#include <QDomDocument> //文件
#include <QDomProcessingInstruction> //格式头部
#include <QDomElement>  //元素
#include <QTextStream> //文件流
#include <QSqlQuery>
#include <QPrinter>
#include <QTextDocument>
#include <QTextBlock>
#include <QDesktopServices>
#include <QUrl>
#define cout qDebug() << "[" << __FILE__ << ":" << __LINE__ << "]"

DocManage::DocManage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DocManage)
{
    ui->setupUi(this);

    initTableWidget();

}

DocManage::~DocManage()
{
    delete ui;
}

//初始化tableWidget
void DocManage::initTableWidget()
{
    //ui->tableWidget->verticalHeader()->setVisible(false); //不显示左边序号
    ui->tableWidget->horizontalHeader()->setFixedHeight(30); //表头高
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);  //整行选中的方式
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);  //设置为可以选中单个
    ui->tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}"); //设置表头的背景色
    ui->tableWidget->setStyleSheet("selection-background-color:rgb(173,216,230);"); //设置选中行的背景色

}

//切换文书
void DocManage::on_buttonChange_clicked()
{
    static int i = 0;
    ui->stackedWidget->setCurrentIndex( ++i % 2 );
}

//添加记录行
void DocManage::on_buttonAdd_clicked()
{
    emit findCadre();
    /*//手工添加记录
    int cols = ui->tableWidget->columnCount();
    int rows = ui->tableWidget->rowCount();
    qDebug() << rows << cols;

    ui->tableWidget->insertRow(rows);

    for(int i=0;i<cols;i++)
    {
        ui->tableWidget->setItem(rows,i,new QTableWidgetItem("new"+QString::number(rows)));
    }

    ui->tableWidget->selectRow(rows);*/
}

//删除记录行
void DocManage::on_buttonDelete_clicked()
{
    int currentRow = ui->tableWidget->currentRow();
    if (currentRow != -1)//如果选中了一行
    {
        QMessageBox::StandardButton result;
        result = QMessageBox::question(this,"确认消息框","确认删除该条记录？",QMessageBox::Yes|QMessageBox::No);
        if(result==QMessageBox::Yes)
        {
            QTableWidgetItem * item = ui->tableWidget->currentItem();

            if(item == 0) return;

            ui->tableWidget->removeRow(item->row());
        }
        else if(result==QMessageBox::No)
        {
            return;
        }
    }
    else
    {
        if (ui->tableWidget->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
        }
    }
}

//交换两行记录数据
void DocManage::SwapTwoRow(int selectRow, int targetRow)
{
    QStringList selectRowLine, targetRowLine;//创建两个QStringList用于储存表格数据
    int colCount = ui->tableWidget->columnCount();
    for (int i = 0; i < colCount; i++)
    {
        selectRowLine.append(ui->tableWidget->item(selectRow, i)->text());//获取文本，并添加进QStringLine
        targetRowLine.append(ui->tableWidget->item(targetRow, i)->text());
    }
    for (int i = 0; i < colCount; i++)
    {
        ui->tableWidget->setItem(selectRow, i, new QTableWidgetItem(targetRowLine.at(i))); //设置文本
        ui->tableWidget->setItem(targetRow, i, new QTableWidgetItem(selectRowLine.at(i)));
    }
}

//上移
void DocManage::on_buttonUp_clicked()
{
    int m_CurrentRow = ui->tableWidget->currentRow();//获取当前行的Index
    if (m_CurrentRow != -1)//如果选中了数据，（未选择数据之前，返回值是-1）
    {
        if (m_CurrentRow != 0)//如果选定行不在第一行
        {
            SwapTwoRow(m_CurrentRow, m_CurrentRow - 1);
            ui->tableWidget->setCurrentCell(m_CurrentRow - 1, QItemSelectionModel::Select);//移动过后继续选定该行
        }
    }
    else
    {
       if (ui->tableWidget->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
       {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
       }
       else
       {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
       }
    }
}

//下移
void DocManage::on_buttonDown_clicked()
{
    int m_CurrentRow = ui->tableWidget->currentRow();
    if (m_CurrentRow != -1)//如果选中了一行
    {
        if (m_CurrentRow != (ui->tableWidget->rowCount() - 1))//如果不是最后一行
        {
            SwapTwoRow(m_CurrentRow, m_CurrentRow + 1);
            ui->tableWidget->setCurrentCell(m_CurrentRow + 1, QItemSelectionModel::Select);//移动过后继续选定该行
        }

    }
    else
    {
        if (ui->tableWidget->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
        }
    }
}

//接收 干部查询界面NUM->chooseCadre NUM
void DocManage::dealRecvNum(QString num)
{
    QString sql = QString("select CadreName,Sex,Birth,NationID,NativePlace,JoinWorkTime,PoliticID,UnitID from CadreInfo where IDNum = '%1'").arg(num);
    QSqlQuery query;
    query.exec(sql);
    while(query.next()) //一行一行遍历
    {
        int rowc = ui->tableWidget->rowCount();//获取行数
        ui->tableWidget->insertRow(rowc);
        //干部名称
        ui->tableWidget->setItem(rowc,0,new QTableWidgetItem(query.value(0).toString()));
        //qDebug()<<query.value(1).toString();
        //性别
        if(query.value(1).toString()== "1")
            ui->tableWidget->setItem(rowc,1,new QTableWidgetItem("男"));
        if(query.value(1).toString()== "0")
            ui->tableWidget->setItem(rowc,1,new QTableWidgetItem("女"));
        //出生时间
        ui->tableWidget->setItem(rowc,2,new QTableWidgetItem(query.value(2).toString()));
        //民族
        QString sqlNation = QString("select Nation from NationCode where NationID = '%1'").arg(query.value(3).toString());
        QSqlQuery queryNation;
        queryNation.exec(sqlNation);
        while(queryNation.next()) //一行一行遍历
        {
            ui->tableWidget->setItem(rowc,3,new QTableWidgetItem(queryNation.value(0).toString()));
        }
        //籍贯
        QString sqlAdminArea = QString("select AdminArea from AdminAreaCode where AdminAreaID = '%1'").arg(query.value(4).toString());
        QSqlQuery queryAdminArea;
        queryAdminArea.exec(sqlAdminArea);
        while(queryAdminArea.next()) //一行一行遍历
        {
            ui->tableWidget->setItem(rowc,4,new QTableWidgetItem(queryAdminArea.value(0).toString()));
        }
        //工作时间
        ui->tableWidget->setItem(rowc,5,new QTableWidgetItem(query.value(5).toString()));
        //政治面貌
        QString sqlPol = QString("select Politic from PoliticCode where PoliticID = '%1'").arg(query.value(6).toString());
        QSqlQuery queryPol;
        queryPol.exec(sqlPol);
        while(queryPol.next()) //一行一行遍历
        {
            ui->tableWidget->setItem(rowc,6,new QTableWidgetItem(queryPol.value(0).toString()));
        }
        //学历（最高）
        QString sqlEduNum = QString("select EduNum from Edu where  IDNum = '%1'").arg(num);
        QSqlQuery queryEduNum;
        queryEduNum.exec(sqlEduNum);
        int eduMaxCode=100;
        while(queryEduNum.next()) //一行一行遍历
        {
            if(queryEduNum.value(0).toInt() < eduMaxCode) eduMaxCode = queryEduNum.value(0).toInt();
        }
        QString sqlEduName = QString("select Education from EducationCode where  EducationID = '%1'").arg(eduMaxCode);
        QSqlQuery queryEduName;
        queryEduName.exec(sqlEduName);
        while(queryEduName.next()) //一行一行遍历
        {
            ui->tableWidget->setItem(rowc,7,new QTableWidgetItem(queryEduName.value(0).toString()));
        }
        //单位
        QString sqlUnit = QString("select unitname from unit where unitid = '%1'").arg(query.value(7).toString());
        QSqlQuery queryUnit;
        queryUnit.exec(sqlUnit);
        while(queryUnit.next()) //一行一行遍历
        {
            ui->tableWidget->setItem(rowc,8,new QTableWidgetItem(queryUnit.value(0).toString()));
        }
        //现任职务
        QString sqlPost = QString("select PostName from Post where QualifyType = '0' and IDNum = '%1'").arg(num);
        QSqlQuery queryPost;
        queryPost.exec(sqlPost);
        while(queryPost.next()) //一行一行遍历
        {
            ui->tableWidget->setItem(rowc,9,new QTableWidgetItem(queryPost.value(0).toString()));
        }
        //何种考察对象（待填）
        ui->tableWidget->setItem(rowc,10,new QTableWidgetItem(""));
    }
}

//导出xml
void DocManage::on_buttonOut_clicked()
{
    QString fileName = QFileDialog::getSaveFileName( this, "Save", "../", "*.xml" );
    if (QFileInfo(fileName).suffix().isEmpty())
    {
        fileName.append(".xml");
    }
    QFile file( fileName );
    /*if( true == file.exists() ) //如果存在不创建
    {
        cout << "文件已经存在";
        return;
    }
    else
    {*/ //不存在才创建
        //只写方式打开文件
        bool isOk = file.open(QIODevice::WriteOnly);
        if(true == isOk)//如果打开成功
        {
            //创建xml文档对象
            QDomDocument doc;
            //创建xml头部格式 <?xml version='1.0' encoding='utf-8'?>
            QDomProcessingInstruction ins;
            ins = doc.createProcessingInstruction("xml", "version=\'1.0\' encoding=\'utf-8\'");
            //追加元素
            doc.appendChild(ins);

            //根节点元素
            QDomElement root = doc.createElement("文书管理");
            doc.appendChild(root);

            //创建文书内容子节点元素
            QDomElement docEmt = doc.createElement("文书内容");
            //把节点追加到根节点上
            root.appendChild(docEmt);

            //文书信息元素
            QDomElement docText = doc.createElement("文书");
            QString strText;

            //选择文书内容
            int docWIndex = ui->stackedWidget->currentIndex();
            if(docWIndex == 0)
            {
                strText = ui->textEdit->toPlainText();
            }
            if(docWIndex == 1)
            {
                strText = ui->textEdit_2->toPlainText();
            }

            QDomText text = doc.createTextNode(strText);
            docText.appendChild(text);

            docEmt.appendChild(docText);

            //附录
            QDomElement apEmt = doc.createElement("附录");
            root.appendChild(apEmt);

            int rowc = ui->tableWidget->rowCount();
            for(int i=0;i<rowc;i++)
            {
                //附录
                QDomElement jlEmt = doc.createElement("记录");
                apEmt.appendChild(jlEmt);

                QDomElement cadreName = doc.createElement("姓名");
                QDomElement sex = doc.createElement("性别");
                QDomElement birth = doc.createElement("出生时间");
                QDomElement nation = doc.createElement("民族");
                QDomElement nativePlace = doc.createElement("籍贯");
                QDomElement joinWorkTime = doc.createElement("工作时间");
                QDomElement politic = doc.createElement("政治面貌");
                QDomElement edu = doc.createElement("学历");
                QDomElement job = doc.createElement("现任职务");
                QDomElement waitSure = doc.createElement("确认何种职务考察对象");

                QString nameText,sexText,birthText,nText,npText,wtText,pText,eText,jText,wsText;
                QDomText text;

                if(ui->tableWidget->item(i,0)){
                    nameText = ui->tableWidget->item(i,0)->text();
                    //qDebug()<< nameText;
                    text = doc.createTextNode(nameText);
                    cadreName.appendChild(text);
                }
                if(ui->tableWidget->item(i,1)){
                    sexText = ui->tableWidget->item(i,1)->text();
                    //qDebug()<< sexText;
                    text = doc.createTextNode(sexText);
                    sex.appendChild(text);
                }
                if(ui->tableWidget->item(i,2)){
                    birthText = ui->tableWidget->item(i,2)->text();
                    //qDebug()<< birthText;
                    text = doc.createTextNode(birthText);
                    birth.appendChild(text);
                }
                if(ui->tableWidget->item(i,3)){
                    nText = ui->tableWidget->item(i,3)->text();
                    //qDebug()<< nText;
                    text = doc.createTextNode(nText);
                    nation.appendChild(text);
                }
                if(ui->tableWidget->item(i,4)){
                    npText = ui->tableWidget->item(i,4)->text();
                    //qDebug()<< npText;
                    text = doc.createTextNode(npText);
                    nativePlace.appendChild(text);
                }
                if(ui->tableWidget->item(i,5)){
                    wtText = ui->tableWidget->item(i,5)->text();
                    //qDebug()<< wtText;
                    text = doc.createTextNode(wtText);
                    joinWorkTime.appendChild(text);
                }
                if(ui->tableWidget->item(i,6)){
                    pText = ui->tableWidget->item(i,6)->text();
                    //qDebug()<< pText;
                    text = doc.createTextNode(pText);
                    politic.appendChild(text);
                }
                if(ui->tableWidget->item(i,7)){
                    eText = ui->tableWidget->item(i,7)->text();
                    //qDebug()<< eText;
                    text = doc.createTextNode(eText);
                    edu.appendChild(text);
                }
                if(ui->tableWidget->item(i,9)){
                    jText = ui->tableWidget->item(i,9)->text();
                    //qDebug()<< jText;
                    text = doc.createTextNode(jText);
                    job.appendChild(text);
                }
                if(ui->tableWidget->item(i,10)){
                    wsText = ui->tableWidget->item(i,10)->text();
                    //qDebug()<< wsText;
                    text = doc.createTextNode(wsText);
                    waitSure.appendChild(text);
                }
                jlEmt.appendChild(cadreName);
                jlEmt.appendChild(sex);
                jlEmt.appendChild(birth);
                jlEmt.appendChild(nation);
                jlEmt.appendChild(nativePlace);
                jlEmt.appendChild(joinWorkTime);
                jlEmt.appendChild(politic);
                jlEmt.appendChild(edu);
                jlEmt.appendChild(job);
                jlEmt.appendChild(waitSure);

            }

            //保存
            QTextStream stream(&file); //文本流关联文件
            doc.save(stream, 4); //4 缩进字符
            file.close(); //关闭文件

            QMessageBox::information(this,"提示","导出成功！");
        }

        else
        {
            cout << "WriteOnly error";
            return;
        }

    //}

}

//形成html
QString DocManage::saveHtmlToPDF(QString fileName)
{
    QString html = "";
    html += "<html>";
    html += "<head>";
    html += "<title>"+fileName+"</title>";
    html += "<head>";
    html += "<body>";
    html += "<h1>公示信息</h1>";
    //html += "</table>";
    QString strText;
    int docWIndex = ui->stackedWidget->currentIndex();
    if(docWIndex == 0)
    {
        strText = ui->textEdit->toPlainText();
    }
    if(docWIndex == 1)
    {
        strText = ui->textEdit_2->toPlainText();
    }
    html += "<hr>";
            html += "<p>" + strText + "</p>";
    html += "</hr>";
    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
        html += "<tr>";
            html += "<td align=\"center\" height=\"60\">------干部信息------</td>";
        html += "</tr>";
    html += "</table>";

    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
    html += "<tr>";
        html += "<th>姓名</th>";
        html += "<th>性别</th>";
        html += "<th>出生时间</th>";
        html += "<th>民族</th>";
        html += "<th>籍贯</th>";
        html += "<th>政治面貌</th>";
        html += "<th>学历</th>";
        html += "<th>现任职务</th>";
        html += "<th>确认何种职务考察对象</th>";
    html += "</tr>";
    int rows_rm = ui->tableWidget->rowCount();
    for(int i=0;i<rows_rm;i++)
    {
        html += "<tr>";
        if(ui->tableWidget->item(i,0)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,0)->text()+"</th>";
        }
        if(ui->tableWidget->item(i,1)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,1)->text()+"</th>";
        }
        if(ui->tableWidget->item(i,2)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,2)->text()+"</th>";
        }
        if(ui->tableWidget->item(i,3)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,3)->text()+"</th>";
        }
        if(ui->tableWidget->item(i,4)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,4)->text()+"</th>";
        }
        if(ui->tableWidget->item(i,6)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,6)->text()+"</th>";
        }
        if(ui->tableWidget->item(i,7)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,7)->text()+"</th>";
        }
        if(ui->tableWidget->item(i,9)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,9)->text()+"</th>";
        }
        if(ui->tableWidget->item(i,10)!=NULL){
            html += "<th>"+ui->tableWidget->item(i,10)->text()+"</th>";
        }

        html += "</tr>";
    }
    html += "</table>";
    html += "</body>";
    html += "</html>";
    return html;
}

//打印-形成pdf并打开
void DocManage::on_buttonPrint_clicked()
{
    QString fileName = QFileDialog::getSaveFileName( this, "导出PDF文件", "../", "*.pdf" );

    if (!fileName.isEmpty())
    {
        // 如果文件后缀为空，则默认使用.pdf
        if (QFileInfo(fileName).suffix().isEmpty())
        {
            fileName.append(".pdf");
        }

        QPrinter *printer = new QPrinter(QPrinter::ScreenResolution);
        // 指定输出格式为pdf
        printer->setPageSize(QPrinter::A4);
        printer->setOutputFormat(QPrinter::PdfFormat);
        printer->setOutputFileName(fileName);

        QTextDocument document;
        document.setHtml(saveHtmlToPDF(fileName));
        document.print(printer);
        document.end();

        QString strPdf = fileName;
        //qDebug()<<strPdf;
        QDesktopServices::openUrl(QUrl::fromLocalFile(strPdf));
    }
}



//选择模板
//void DocManage::chooseFile()
//{
//    //远程文件：getOpenFileUrl
//    QString filePath = QFileDialog::getOpenFileName(
//                this,
//                "Open File",
//                "/home/TimiWang/QT/templet",
//                "word(*.doc *.docx *.odt);;text(*.txt);;all(*.*)"
//                              );
//    qDebug() << filePath;

//    //如果用户直接关闭了文件浏览对话框，那么文件名就为空值，直接返回
//    if(filePath == "")
//       {
//          return;
//    }
//    else
//        {
//            QFile file(filePath);
//            bool isOk = file.open(QIODevice::ReadOnly);
//            if(true == isOk)
//               {
//                   QTextStream stream(&file);
//                   //指定编码
//                   stream.setCodec("UTF-8");
//                   QString str = stream.readAll();
//                   ui->textEdit->setText(str);
//                   file.close();
//               }
//    }
//}

//添加模板
//void DocManage::addFile()
//{
//    //TCP传文件？？？
//    QString filePath = QFileDialog::getOpenFileName(
//                this,
//                "Open File",
//                "../QT/templet/",
//                "word(*.doc *.docx *.odt);;text(*.txt);;all(*.*)"
//                              );
//    qDebug() << filePath;
//}
